import uuid
from datetime import datetime
from common.database import db
from model.user import User
from result.result import Result
from result.result_code import ResultCode
from utils.check_data import check_data
from utils.to_md5 import to_md5
from flask_jwt_extended import create_access_token, get_jwt_identity
from utils.verify_code import verify_code


class UserService(object):

    @staticmethod
    def add_user(data):
        if not check_data(data, ["name", "email", "password", "code"]):
            return Result.error(ResultCode.DATA_ERROR.value, "必填项不可为空")
        users = UserService.select_by_email(data['email'])
        if len(users) > 0:
            return Result.error(ResultCode.DATA_CHECK_ERROR.value, "邮箱已经存在")
        try:
            # verify = Verify.query.filter_by(email=data['email']).first()
            # if verify is None:
            #     return Result.error(ResultCode.DATA_CHECK_ERROR.value, "未获取验证码")
            # elif verify.val_time < datetime.now():
            #     return Result.error(ResultCode.DATA_CHECK_ERROR.value, "验证码已过期")
            # elif verify.code != data['code']:
            #     return Result.error(ResultCode.DATA_CHECK_ERROR.value, "验证码错误")
            check_str = verify_code(data['email'], data['code'])
            if check_str:
                return Result.error(ResultCode.DATA_CHECK_ERROR.value, check_str)
            else:
                user = User(id=uuid.uuid4(), name=data['name'], email=data['email'], password=to_md5(data['password']),
                            register_time=datetime.now())
        except Exception as e:
            print(e)
            return Result.error(ResultCode.DATA_ERROR.value, "您传入的注册信息有误，请检查注册信息是否完整或格式是否有误")
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            print(e)
            return Result.error(ResultCode.DATABASE_ERROR.value, "DATABASE ERROR")
        return Result.success()

    @staticmethod
    def select_by_email(email):
        return User.query.filter_by(email=email).all()

    @staticmethod
    def select_all():
        result = User.query.all()
        return result

    @staticmethod
    def check_psd(data):
        if not check_data(data, ["email", "password"]):
            return Result.error(ResultCode.DATA_ERROR.value, "必填项不可为空")
        user = UserService.select_by_email(data["email"])
        if len(user) == 0:
            return Result.error(ResultCode.DATA_CHECK_ERROR.value, "此邮箱还未注册")
        elif to_md5(data["password"]) != user[0].password:
            return Result.error(ResultCode.DATA_CHECK_ERROR.value, '密码错误')
        else:
            access_token = create_access_token(identity=data['email'])
            return Result.success_data('Bearer ' + access_token)

    @staticmethod
    def info():
        email = get_jwt_identity()
        try:
            # print(email)
            user = UserService.select_by_email(email)[0]
            # print(user.name)
            return Result.success_data(user.to_dict())
        except Exception as e:
            print(e)
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.value, "服务器出错")

    @staticmethod
    def upload_psd(data):
        if not check_data(data, ["email", "new_psd", "code"]):
            return Result.error(ResultCode.DATA_ERROR.value, "必填项不可为空")
        email = data['email']
        new_psd = to_md5(data['new_psd'])
        code = data['code']
        user = User.query.filter_by(email=email).first()
        if user is None:
            return Result.error(ResultCode.DATA_CHECK_ERROR.value, "邮箱没有注册")
        check_str = verify_code(email, code)
        if check_str:
            return Result.error(ResultCode.DATA_CHECK_ERROR.value, check_str)
        else:
            user.password = new_psd
            db.session.commit()
            return Result.success()



